package com.future;

import java.util.Arrays;

/**
 * Description: 532. 数组中的 k-diff 数对
 *
 * @author weiruibai.vendor
 * Date: 2023/2/21 15:08
 */
public class Solution_532 {

    private static Solution_532 instance = new Solution_532();

    public static void main(String[] args) {
        int[] nums = new int[]{3, 1, 4, 1, 5};
        int k = 2;
        nums = new int[]{1, 1, 2, 2};
        nums = new int[]{1, 1, 3, 4, 5};
        k = 0;
        System.out.println(instance.findPairs(nums, k));
    }

    public int findPairs(int[] nums, int k) {
        int ans = 0;
        Arrays.sort(nums);
        int N = nums.length;
        int l = 0, r = 1;
        while (l < r && r < N) {
            int minus = nums[r] - nums[l];
            if (minus == k) {
                while (l + 1 < N && nums[l] == nums[l + 1]) {
                    l++;
                }
                l++;
                while (r + 1 < N && nums[r] == nums[r + 1]) {
                    r++;
                }
                r++;
                ans++;
            } else if (minus < k) {
                while (r + 1 < N && nums[r] == nums[r + 1]) {
                    r++;
                }
                r++;
            } else {
                while (l + 1 < N && nums[l] == nums[l + 1]) {
                    l++;
                }
                l++;
            }
            if (l == r) {
                r++;
            }
        }
        return ans;
    }


}
